#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "main.h"
//#include "pass_time.h"//#define MEMBER_ID_BASE   100001

// 全局变量定义
Member users[MAX_USERS];
int user_count = 0;

//获取当前日期
Date get_current_date(){
	time_t t = time(NULL);
	struct tm tm = *localtime(&t);
	Date current = {tm.tm_year + 1900, tm.tm_mon + 1,tm.tm_mday};
	return current;
}/*
// 添加目录创建函数
void ensure_directory_exists() {
    mkdir("/root/code/xiang/xiang/data", 0777);
    mkdir("/root/code/xiang/xiang/data/files", 0777);
}*/
/*static unsigned int get_new_min(void){
	Member mi;
	unsigned int card_id;

	FILE* fp = fopen(FILENAME,"rb");
	if(fp == NULL){
		return MEMBER_ID_BASE;
	}

	fseek (fp,-sizeof(mi),SEEK_END);

	if(fread(&mi,sizeof(mi),1,fp) == 1){
		mid = mi->mid + 1;
	}else{
		mid = MEMBER_ID_BASE;
	}
	fclose(fp);
	return mid;
}*/
//保存会员信息到文件
void save_to_file(){
	
	FILE *fp = fopen(FILENAME,"wb");
	if(fp == NULL){
		printf("无法打开文件进行写入！\n");
		return;
	}
	//写入总用户数量 user_count
	fwrite(&user_count,sizeof(int),1,fp);
	//写入users数组
	for(int i = 0; i < user_count; i++) {
        	fwrite(&users[i], sizeof(Member), 1, fp);
    	}
	//fwrite(users,sizeof(Member),user_count,fp);
	fclose(fp);
	printf("用户信息保存成功！");

}

//从文件中加载会员信息
void load_from_file(){
	FILE *fp = fopen(FILENAME, "rb");
	if(fp == NULL){
		printf("未找到会员数据文件，将创建新文件\n");
		return;
	}

	// 读取 user_count
	if(fread(&user_count, sizeof(int), 1, fp) != 1){
		printf("读取用户数量失败！\n");
		fclose(fp);
		return;
	}

	// 读取 users 数组
	for(int i = 0; i < user_count; i++) {
     		if(fread(&users[i], sizeof(Member), 1, fp) != 1) {
        		printf("读取用户数据失败！\n");
                	break;
        	}
        }
	//fread(users, sizeof(Member), user_count, fp);
	fclose(fp);
	printf("会员信息已加载！\n");
/*
	int max_num = find_max_card_num();
  	set_next_card_num(max_num + 1);
*/
	}
/*
void get_new_card_id(char *new_card_id) {
    static int next_card_num = 1000; // 从1000开始，静态变量保持值
    sprintf(new_card_id, "%d", next_card_num);
    next_card_num++;
}

int find_max_card_num() { //找最大卡号
    int max_num = 1000 - 1; // 初始为999，这样第一个是1000
    for (int i = 0; i < user_count; i++) {
        int num = atoi(users[i].card_id);
        if (num > max_num) {
            max_num = num;
        }
    }
    return max_num;
}
*/

void user_reg() // 添加用户
{	
	if(user_count >= MAX_USERS){
		printf("当前用户已达上限,无法注册\n");
		return ;
	}

	Member *p = &users[user_count];
	
	printf("\n<<<<<<录入会员信息>>>>>>\n");
	

	//Member new_user;
	//get_new_card_id(new_user.card_id); // 生成新卡号
	
	//卡号
	//p.card_id = get_new_min();	
	
	printf("请输入卡号: ");
	scanf("%19s", p->card_id);
	getchar(); // 清除缓冲区

	// 用户ID
	printf("请输入用户ID: ");
	scanf("%19s", p->user_id);
	getchar();

	// 姓名
	printf("请输入姓名: ");
	scanf("%49[^\n]", p->name); // 读取整行，直到遇到换行符
	getchar();

	// 性别
	printf("请输入性别(M-男/F-女/O-其他): ");
	scanf("%c", &p->gender);
	getchar();

	// 生日
	printf("请输入生日(年 月 日，用空格分隔): ");
	scanf("%d %d %d", &p->birthday.year, &p->birthday.month, &p->birthday.day);
	getchar();

	// 手机号
	printf("请输入手机号: ");
	scanf("%14s", p->phone);
	getchar();

	// 注册时间
	p->register_date = get_current_date();
	p->register_timestamp = time(NULL); //注册时间戳
	// 会员类型
	printf("请选择会员类型(1-次卡 2-月卡 3-年卡 ): ");
	int type;
	scanf("%d", &type);
	getchar();
	p->type = (MemberType)(type - 1);
	//struct tm* lc_time;
/*
	Member newuser;
	long now_time = time(NULL);	//获取时间戳
	lc_time = localtime(&now_time);	//获取本地时间
	newuser.eff_time = new_user.resign_time = now_time;	//初始化失效日期和注册日期
*/
	time_t now = time(NULL);
	const long month_seconds = 30*86400; //30天的时间戳
	const long year_seconds = 365*86400; //365天的时间戳

	
	if(p->type == times_card){
		printf("请输入剩余次数：");
		scanf("%d", &p->remaining_times);//获取注册时间
		getchar();
	}
	else if(p->type == month_card) {
		p->expire_timestamp = now + month_seconds; //月卡加上一个月时间
		p->remaining_times = -1;
	}
	else  {
		p->expire_timestamp = now + year_seconds;
		p->remaining_times = -1;
	}

/*	//
	MemberType.reg_time = get_current_date();;

	if(type == month_card)
		const long month_time = 30*86400; //30天的时间戳
	else

		const long year_time = 365*86400; //365天的时间戳
	mi.mid = get_new_mid();
*/
	p->delete_state = 0; // 初始化删除状态为0（未删除）

	user_count++;
	printf("\n会员注册成功！\n");
	
	save_to_file();//调用保存文件函数
}


void user_mod(void) // 修改用户信息
{
	char num[50];
	int found_index = -1;
	
	system("clear");  // 清屏
	printf("请输入要修改的会员卡号/ID/手机号\n");
	scanf("%49s",num);
	getchar();
	bool found = false;
	for(int i = 0;i < user_count;i++){
		if(users[i].delete_state == 1){
			continue;
		}
		if(strcmp(users[i].card_id,num) ==0 || strcmp(users[i].user_id,num) == 0|| strcmp(users[i].phone,num) == 0) {
			found = true;
			printf("您的信息如下：\n");
			display_member_info(&users[i]);
			found_index = i;
		}
	}
	if(found == false) {
		printf("未找到您的信息\n");	
			return ;
	}

	Member* p = &users[found_index];
	int choice;
	do{
		printf("选择您要修改的信息：\n");
		printf("1 - 修改手机号\n");
		printf("2 - 修改姓名\n");
		printf("3 - 修改会员ID\n");
		printf("4 - 修改生日\n");
		printf("5 - 修改剩余次数\n");
		printf("0 - 退出！\n");
		scanf("%d",&choice);
		getchar();

		switch(choice){
			case 0:
				printf("返回主菜单\n");
				break;
			case 1:
				printf("修改手机号\n");
				scanf("%14s",p->phone);
				getchar();
				printf("手机号已修改成功！\n");
				break;
			case 2:
				printf("修改姓名:\n");
				scanf("%49s",p->name);
				getchar();
				printf("姓名已修改成功！\n");
				break;
			case 3:
				printf("修改会员ID\n");
				scanf("%14s",p->user_id);
				getchar();
				printf("会员ID已修改成功\n");
				break;
			case 4:
				printf("修改生日\n");
				scanf("%d%d%d",&p->birthday.year,&p->birthday.month,&p->birthday.day);
				printf("修改会员生日已成功\n");
				break;
			case 5:
				printf("修改剩余次数\n");
				scanf("%d",&p->remaining_times);
				printf("会员剩余次数已修改！\n");
				break;
			default:
				printf("无效输入，请重新输入！\n");

		}

		if(choice != 0){
			save_to_file();
		}
	}while(choice != 0);
}


void user_del(void) // 删除用户信息
{
	char num[50];
	
	system("clear");  // 清屏
	printf("请输入要删除的会员卡号/ID/手机号\n");
	scanf("%49s",num);
	getchar();

	bool found = false;
	for(int i = 0;i < user_count;i++ ){
		if(users[i].delete_state == 1){
			continue;
		}

		if(strcmp(num,users[i].card_id ) == 0 ||strcmp(num,users[i].user_id) == 0 || strcmp(num,users[i].phone) == 0){
			found = true;
			printf("您的信息如下：\n");
			display_member_info(&users[i]);
			printf("确认删除吗？\n");
			char confirm;
			scanf("%c",&confirm);
			getchar();

			if (confirm == 'Y' || confirm == 'y') {
				users[i].delete_state = 1; // 标记为已删除
				save_to_file(); // 保存到文件
				printf("会员删除成功！\n");
			} else {
				printf("取消删除操作。\n");
			}
			break;
		}
	}

	if(!found){
		printf("未找到会员信息，请联系工作人员");
	}
}


void search_member(){	//查询个人信息主菜单
	int choice;
	
	system("clear");  // 清屏
	do{
		printf("\n===== 查询会员信息 =====\n");
		printf("1. 按卡号查询\n");
		printf("2. 按用户ID查询\n");
		printf("3. 按手机号查询\n");
		printf("0. 返回主菜单\n");
		printf("请选择查询方式: ");
		scanf("%d", &choice);
		getchar();

		switch(choice){
			case 1:
			       search_by_card_id();
			       break;
			case 2:
			       search_by_user_id();
			       break;
			case 3:
			       search_by_phone();
			       break;
			case 0:
				printf("返回主菜单\n");
				break;
			default:
				printf("无效选择，请重新输入！\n");
		}
	
	}while(choice != 0);
}


void search_by_card_id(){ // 根据卡号查询个人信息
	char search_id[20];
	system("clear");  // 清屏

	printf("请输入要查询的卡号");
	scanf("%19s",search_id);
	getchar();

	bool found = false;
	for(int i = 0; i< user_count;i++){
		if(users[i].delete_state == 1){
			continue;
		}
		if(strcmp(users[i].card_id,search_id) == 0){
			display_member_info(&users[i]);
			found = true;
			break;
		}
	}
	if(!found){
		printf("\n未找到卡号为%s的会员\n",search_id);
	}
}

void search_by_user_id(){ // 通过用户 ID 查找
	char search_id[20];
	system("clear");  // 清屏
	printf("请输入要查询的用户ID\n");
	scanf("%19s",search_id);
	getchar();

	bool found = false;
	for(int i =0;i<= user_count; i++){
               if(users[i].delete_state == 1){
                        continue;
                }
		if(strcmp(users[i].user_id,search_id) == 0){
			display_member_info(&users[i]);
			found = true;
			break;
		}
	}
	if(!found){
		printf("\n未找到用户ID为%s的会员\n",search_id);
	}



}


// 根据手机号查询
void search_by_phone() {
	char search_phone[15];
	system("clear");  // 清屏
	printf("请输入要查询的手机号: ");
	scanf("%14s", search_phone);
	getchar();

	bool found = false;
	for (int i = 0; i < user_count; i++) {
		if(users[i].delete_state == 1){
			continue;
		}

		if (strcmp(users[i].phone, search_phone) == 0) {
			display_member_info(&users[i]);
			found = true;
			break;
		}
	}

	if (!found) {
		printf("\n未找到手机号为 %s 的会员\n", search_phone);
	}
}


// 显示单个会员信息
void display_member_info(const Member *p) {
	const char *type_str[] = {"次卡", "月卡", "年卡", "VIP卡"};


	printf("\n\n\n===== 会员详细信息 =====\n");
	printf("=========================\n");
	printf("卡号: %s\n", p->card_id);
	printf("用户ID: %s\n", p->user_id);
	printf("姓名: %s\n", p->name);
	printf("性别: %c\n", p->gender);
	printf("生日: %d年%d月%d日\n", p->birthday.year, p->birthday.month, p->birthday.day);
	printf("手机号: %s\n", p->phone);
	printf("注册日期: %d年%d月%d日\n", p->register_date.year, p->register_date.month, p->register_date.day);
	printf("会员类型: %s\n", type_str[p->type]);

	// 显示过期信息
    	display_expire_info(p);

	printf("=========================\n");
	printf("=========================\n");

	//void press_any_key(void);
}


const char *type_str[] = {"次卡", "月卡", "年卡", "VIP卡"};
void user_allsea(void) // 查看所有用户信息 
{	
	system("clear");  // 清屏
	printf("\n<<<<<< 所有会员信息 >>>>>>\n");
	for (int i = 0; i < user_count; i++) {
		if(users[i].delete_state == 1){
			continue;
		}


		Member *p = &users[i];

		printf("\n会员 %d:\n", i+1);
		printf("卡号: %s\n", p->card_id);
		printf("用户ID: %s\n", p->user_id);
		printf("姓名: %s\n", p->name);
		printf("性别: %c\n", p->gender);
		printf("生日: %d年%d月%d日\n", p->birthday.year, p->birthday.month, p->birthday.day);
		printf("手机号: %s\n", p->phone);
		printf("注册日期: %d年%d月%d日\n", p->register_date.year, p->register_date.month, p->register_date.day);
		printf("会员类型: %s\n", type_str[p->type]);

		display_expire_info(p);//显示会员卡过期信息

		printf("=========================\n");
		printf("\n\n");
	}	
	//void press_any_key(void);
}
